// pages/bangdingweixin/bangdingweixin.js
const utilbase = require('../../../../utils/setpwdbase64');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    yanzhengm: '',
    personname: '',
    yzmTime: 60,
    weixinzh: '', //账户名
    account: '', //openID
    img: '', //头像
    showModal: false, //add弹窗
    mima: '', //密码
    isFocus: false, //控制input 聚焦
  },
  //忘记密码
  towangji() {
    wx.navigateTo({
      url: '/pages/setting/page/shezhi/jiaoyishezhi/jiaoyishezhi',
    })
  },
  setpassword(e) {
    let that = this
    that.setData({
      mima: e.detail.value
    })
    if (e.detail.value.length > 5) {
      wx.request({
        url: app.globalData.myurl,
        data: {
          cmd: "upBindAccount",
          shopId: wx.getStorageSync('shopId'),
          userId: wx.getStorageSync('userId'),
          mobile: that.data.phone,
          img: that.data.img,
          acctype: 2,
          appType:1, // 提现应用（0-管理端APP 1-管理端小程序）
          account: that.data.account,
          bname: that.data.weixinzh,
          accname: that.data.personname,
          smsCode: that.data.yanzhengm,
          tpassword: utilbase.base64encode(utilbase.utf16to8(that.data.mima)),
          bankCode: ''
        },
        header: {
          "content-type": "application/x-www-form-urlencoded",
          "token": wx.getStorageSync('token')
        },
        success(res) {
          if (res.data.zjstate == 1) {
            setTimeout(function () {
              wx.hideLoading()
              wx.stopPullDownRefresh() //停止下拉刷新
            }, 0)
            setTimeout(function () {
              wx.showModal({
                title: '您的账号已在其他设备登录，请重新登录！',
                showCancel: false, //是否显示取消按钮false去掉取消按钮
                success: function (res) {
                  if (res.confirm) {
                    wx.clearStorageSync()
                    wx.reLaunch({
                      url: '/pages/login/login',
                    })
                  } else {
                    wx.clearStorageSync()
                    wx.reLaunch({
                      url: '/pages/login/login',
                    })
                  }
                }
              })
            }, 0)
            return
          }
          console.log(res)
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
          if (res.data.result == 0) {
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            }, 1500)
          }
        }
      });
    }
  },
  // 获取焦点
  getjiaodian() {
    this.setData({
      isFocus: true
    })
  },
  // add弹窗
  close_mask: function() {
    this.setData({
      showModal: false
    })
  },
  // 提交绑定
  tijiao() {
    let that = this
    if (!that.data.personname) {
      wx.showToast({
        title: '请输入您的真实姓名',
        icon: 'none'
      })
      return
    }
    if (!that.data.account) {
      wx.showToast({
        title: '请点击绑定微信账户',
        icon: 'none'
      })
      return
    }
    if (!that.data.phone) {
      wx.showToast({
        title: '请输入您绑定的手机号',
        icon: 'none'
      })
      return
    }
    if (!that.data.yanzhengm) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      })
      return
    }
    // 显示密码弹窗
    that.setData({
      showModal: true,
      isFocus: true, //控制input 聚焦
      mima: ''
    })

  },
  // 获取 用户的openID
  checkPermission: function(e) {
    let that = this
    that.setData({
      weixinzh: ''
    })
    if (e.detail.userInfo) {
      // 有授权的操作
      console.log(e.detail.userInfo)
      // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
      wx.login({
        success: function success(res) {
          var code = res.code; //登录凭证
          wx.setStorageSync("code", code);
          if (code) {
            //2、调用获取用户信息接口
            wx.getUserInfo({
              success: function success(res) {
                console.log({
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  code: code
                });
                //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
                wx.request({
                  url: app.globalData.myurlshouquan, //自己的服务接口地址
                  method: "post",
                  header: {
                    "content-type": "application/x-www-form-urlencoded",
                    // "token": wx.getStorageSync('token')
                  },
                  data: {
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                    code: code
                  },
                  success: function success(data) {
                    console.log(data, '待解密');
                    //4.解密成功后 获取自己服务器返回的结果
                    if (data.data.status == 1) {
                      var userInfo_ = data.data.userInfo;
                      // console.log(userInfo_);
                      var userid = data.data.userInfo.openId;
                      var rctoken = data.data.rctoken;
                      // wx.setStorageSync("userid", userid);
                      // wx.setStorageSync("rctoken", rctoken);
                      // wx.setStorageSync("userInfo", data.data.userInfo);
                      that.setData({
                        weixinzh: data.data.userInfo.nickName,
                        account: userid,
                        img: data.data.userInfo.avatarUrl,
                      })
                    } else {
                      // console.log("解密失败");
                    }
                  },
                  fail: function fail() {
                    // console.log("系统错误");
                  }
                });
              },
              fail: function fail() {
                // console.log("获取用户信息失败");
              }
            });
          } else {
            // console.log("获取用户登录态失败！" + r.errMsg);
          }
        },
        fail: function fail() {
          // console.log("登陆失败");
        }
      });
    } else {
      // 没有授权的操作
    }
  },
  // 电话
  getphone(e) {
    let that = this
    that.setData({
      phone: e.detail.value
    })
  },
  // 验证码
  getyanzhengm(e) {
    let that = this
    that.setData({
      yanzhengm: e.detail.value
    })
  },
  // 姓名
  getxingm(e) {
    let that = this
    that.setData({
      personname: e.detail.value
    })
  },
  // 验证码
  huoQu() {
    let that = this
    var telStr = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
    var inputStr = that.data.phone
    if (!(telStr.test(inputStr))) {
      wx.showToast({
        title: '手机号码输入不规范',
        icon: 'none'
      })
      return
    }
    that.setData({
      yzmTime: 59
    })
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "phoneMSCode",
        userPhone: that.data.phone
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        setTimeout(function() {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none'
          })
        }, 0)
      }
    });
    var interval = setInterval(function timestampToTime() {
      var date = that.data.yzmTime
      if (date <= 1) {
        that.setData({
          yzmTime: 60
        })
        clearInterval(interval)
      } else {
        date--
        that.setData({
          yzmTime: date
        })
        console.log(date)
      }
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      phone: wx.getStorageSync('telephone'),
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      showModal: false, //add弹窗
      mima: '', //密码
      isFocus: false, //控制input 聚焦
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '众商联采',
      path: "/pages/login/login", // 路径，传递参数到指定页面。
      // imageUrl:'../../../images/logo/LOGO.png'
      imageUrl: app.globalData.logo
    }
  }
})